package com.it.demo.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/responseServlet")
public class ResponseHeaderServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ResponseHeaderServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String type = request.getParameter("getType");

        switch (type) {
            case "excel":
                PrintWriter out = response.getWriter();
                response.setContentType("application/vnd.ms-excel"); // 输出excel PrintWriter
                out = response.getWriter();
                out.println("\tQ1\tQ2\tQ3\tQ4\tTotal");
                out.println("Apples\t78\t78\t92\t29\t=SUM(B2:E2)");
                out.println("Oranges\t77\t86\t93\t30\t=SUM(B3:E3)");
                break;
            case "html":
                PrintWriter out1 = response.getWriter();
                response.setHeader("refresh", "1"); // 可以使浏览器刷新,一直发送请求
                System.err.println("打印刷新 refresh ");
                response.setContentType("text/html;charset=utf-8");

                out1.println("<!DCTYPE HTML>");
                out1.println("<HEAD><TITLE>A Servlet</TITLE></HEAD>");
                out1.println("  <BODY>");
                out1.println("    当前页面刷新时间为： ");
                out1.println(new Date());
                out1.println("   </BODY>");
                out1.println("</HTML>");
                out1.flush();
                out1.close();
                break;
            case "image":
                response.setContentType("image/jpeg");
                InputStream in = this.getClass().getClassLoader().getResourceAsStream("girl.jpg");
                int len = in.available();
                byte[] buffer = new byte[len];
                in.read(buffer);
                OutputStream outputStream = response.getOutputStream();
                outputStream.write(buffer);
                outputStream.close();
                break;
            default:
                PrintWriter out2 = response.getWriter();
                response.setContentType("text/html;charset=utf-8");
                out2.println("参数类型:excel,html,image...参考read.md文件");
                out2.flush();
                out2.close();
                break;
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

}
